package com.bbg.amyam.web.util.image;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.springframework.web.multipart.MultipartFile;

import static org.imgscalr.Scalr.*;

public class ImageUtils {

	public static byte[] resizeImage(MultipartFile content,int targetWidth, int targetHeight) throws IOException{
		String imageType = content.getContentType().replaceAll("image/", "");
		BufferedImage img = ImageIO.read(content.getInputStream());
		BufferedImage resized = createThumbnail(img,targetWidth,targetHeight);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write( resized, imageType, baos );
		baos.flush();
		byte[] imageInByte = baos.toByteArray();
		baos.close();
		return imageInByte;
	}
	
	private static BufferedImage createThumbnail(BufferedImage img,int targetWidth, int targetHeight) {
		  // Create quickly, then smooth and brighten it.
		if(targetHeight==0){
			img = resize(img, Method.SPEED, targetWidth, OP_ANTIALIAS, OP_BRIGHTER);
		}else{
		  img = resize(img, Method.SPEED, targetWidth, targetHeight, OP_ANTIALIAS, OP_BRIGHTER);
		}
		  // Let's add a little border before we return result.
		  return pad(img, 1);
		}
}
